﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace Axiom.Hermetica
{
	public static class Extensions
	{
		public static List<T> ToDecompressedDataList<T>(this byte[] bytes)
		{
			List<T> data = null;
			using (MemoryStream ms = new MemoryStream(bytes))
			using (GZipStream zs = new GZipStream(ms, CompressionMode.Decompress))
			{
				BinaryFormatter bf = new BinaryFormatter();
				ms.Position = 0;
				data = bf.Deserialize(zs) as List<T>;
			}
			return data;
		}

		public static string ReadLine(this string value)
		{
			var line = string.Empty;
			using (var sr = new StringReader(value))
			{
				line = sr.ReadLine();
			}
			return line;
		}

		public static bool IdenticalTo(this byte[] A, byte[] B)
		{
			if (A == null && B == null)
			{
				return true;
			}
			if (A == null || B == null || A.Length != B.Length)
			{
				return false;
			}

			for (int i = 0; i < A.Length; i++)
			{
				if (A[i] != B[i])
				{
					return false;
				}
			}
			return true;
		}

		public static string CreateNameFromMangledString(this string value)
		{
			string result = null;
			if (string.IsNullOrWhiteSpace(value))
			{
				return string.Empty;
			}

			result = value;

			result = Regex.Replace(result, @"(\d){5}", @" ");

			if (Regex.Matches(result, @"([\.\-_])").Count > 3)
			{
				result = Regex.Replace(result, @"([\.\-_])", @" ");
			}

			result = Regex.Replace(result, @"(\W\W)", " ").Trim();

			return result;
		}

		public static string CamelToTitleCase(this string value)
		{
			string result = null;

			if (string.IsNullOrWhiteSpace(value))
			{
				return string.Empty;
			}
			Regex regex = new Regex(@"(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])", RegexOptions.Compiled);

			result = regex.Replace(value.Replace("_", ""), " $1").Trim();

			result = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(result);
			
			return result;
		}
	}
}
